package com.foxchen.decrypt.service;

import com.zaxxer.hikari.HikariConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.DefaultResourceLoader;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class DbInitService {

    @SuppressWarnings("all")
    public static void init(HikariConfig hikariConfig) throws Exception {
        log.info("begin database init.");
        String jdbcUrl = hikariConfig.getJdbcUrl();
        String poetize = jdbcUrl.substring(0, jdbcUrl.indexOf("poetize")) + "?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";

        try(Connection connection = DriverManager.getConnection(poetize, hikariConfig.getUsername(), hikariConfig.getPassword());
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SHOW DATABASES LIKE 'poetize';")){

            if (!resultSet.next()) {
                log.info("database is not exists,begin create...");
                DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader(DbInitService.class.getClassLoader());

                org.springframework.core.io.Resource resource = defaultResourceLoader.getResource("poetize.sql");

                // 创建表
                try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()))){
                    // 拿到插入数据的sql
                    List<String> insertSqlList = new ArrayList<>();

                    // 筛选掉插入数据的sql后，执行创表sql
                    String sql = bufferedReader
                            .lines()
                            .filter(line -> {
                                // 判断是否是完整的一行
                                boolean insertSql = StringUtils.isNotBlank(line) && (line.startsWith("INSERT")) && line.endsWith(";");
                                if(insertSql){
                                    insertSqlList.add(line);
                                }

                                return !insertSql && !StringUtils.contains(line,"--");
                            })
                            .collect(Collectors.joining("\n"));
                    Arrays.stream(sql.split(";")).forEach(splitSql -> {
                        try {
                            statement.execute(splitSql);
                        } catch (SQLException e) {
                            throw new RuntimeException(e);
                        }
                    });

                    // 再执行插入数据sql
                    for (String insertSql : insertSqlList) {
                        statement.execute(insertSql);
                    }
                    log.info("database create ok...");
                }
                return;
            }
            log.info("database exists...");
        }
    }
}
